//
//  LottilePreviewVC.m
//  LottieFilesPreview
//
//  Created by SssssQG on 2021/3/10.
//

#import "LottilePreviewVC.h"
#import <Lottie.h>
@interface LottilePreviewVC ()

@property (nonatomic, strong) LOTAnimationView *animation;

@end

@implementation LottilePreviewVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self playLottieFile];
    
    self.titleLLab.text = self.fileName;
}

- (void)playLottieFile {
    
    self.animation = [[LOTAnimationView alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.filePath]];
    self.animation.contentMode = UIViewContentModeScaleAspectFit;
    [self.centerView addSubview:self.animation];
    [self.view setNeedsLayout];

}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.animation.frame = self.centerView.bounds;
}


- (IBAction)closeBtnClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)playBtnClick:(UIButton *)sender {
    if (self.animation.isAnimationPlaying) {
        sender.selected = NO;
      [self.animation pause];
    } else {
      
      CADisplayLink *displayLink =[CADisplayLink displayLinkWithTarget:self selector:@selector(_updateSlider)] ;
      [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        sender.selected = YES;
      [self.animation playWithCompletion:^(BOOL animationFinished) {
        [displayLink invalidate];
          sender.selected = NO;
      }];
    }
}
- (IBAction)sliderChange:(UISlider *)sender {
    self.animation.animationProgress = self.slider.value;
}

- (void)_updateSlider {
    self.slider.value = self.animation.animationProgress;
}
@end
